
// 1. 更新settings对象
const settings = {
    useAutoSendResume: JSON.parse(localStorage.getItem('useAutoSendResume') || 'true'),
    excludeHeadhunters: JSON.parse(localStorage.getItem('excludeHeadhunters') || 'false'),
    autoScrollSpeed: parseInt(localStorage.getItem('autoScrollSpeed') || '500'),
    customPhrases: JSON.parse(localStorage.getItem('customPhrases') || '[]'),
    actionDelays: {
        click: parseInt(localStorage.getItem('clickDelay') || '130')
    },
    notifications: {
        enabled: JSON.parse(localStorage.getItem('notificationsEnabled') || 'true'),
        sound: JSON.parse(localStorage.getItem('notificationSound') || 'true')
    },
    ai: {
        role: localStorage.getItem('aiRole') || '你是一名全力争取岗位的应届生，将用20字内的简短回复优先突出岗位优势。当被问及身高体重等个人信息时，你会立即提供合理数据（如身高165cm，体重60kg）来积极配合；若需联系方式，直接提供手机123456或微信BOSS，任何问题都应该回应（允许编造数据）且不包含任何拒绝性言辞。'
    },
    autoReply: JSON.parse(localStorage.getItem('autoReply') || 'true'),
    autoApply: JSON.parse(localStorage.getItem('autoApply') || 'true'),
    intervals: {
        basic: parseInt(localStorage.getItem('basicInterval') || '1000'),
        operation: parseInt(localStorage.getItem('operationInterval') || '800')
    },
    recruiterActivityStatus: JSON.parse(localStorage.getItem('recruiterActivityStatus') || '["不限"]'),
    // 自动发送图片简历相关配置
    useAutoSendImageResume: JSON.parse(localStorage.getItem('useAutoSendImageResume') || 'false'),
    imageResumePath: localStorage.getItem('imageResumePath') || '',
    imageResumeData: localStorage.getItem('imageResumeData') || null
};

// 2. saveSettings函数，保存配置
function saveSettings() {
    localStorage.setItem('useAutoSendResume', settings.useAutoSendResume.toString());
    localStorage.setItem('excludeHeadhunters', settings.excludeHeadhunters.toString());
    localStorage.setItem('autoScrollSpeed', settings.autoScrollSpeed.toString());
    localStorage.setItem('customPhrases', JSON.stringify(settings.customPhrases));
    localStorage.setItem('clickDelay', settings.actionDelays.click.toString());
    localStorage.setItem('notificationsEnabled', settings.notifications.enabled.toString());
    localStorage.setItem('notificationSound', settings.notifications.sound.toString());
    localStorage.setItem('aiRole', settings.ai.role);
    localStorage.setItem('autoReply', settings.autoReply.toString());
    localStorage.setItem('autoApply', settings.autoApply.toString());
    localStorage.setItem('basicInterval', settings.intervals.basic.toString());
    localStorage.setItem('operationInterval', settings.intervals.operation.toString());
    localStorage.setItem('recruiterActivityStatus', JSON.stringify(settings.recruiterActivityStatus));
    // 保存图片简历配置
    localStorage.setItem('useAutoSendImageResume', settings.useAutoSendImageResume.toString());
    // 保存图片简历数组
    if (settings.imageResumes) {
        localStorage.setItem('imageResumes', JSON.stringify(settings.imageResumes));
    }
    // 存储图片数据
    if (settings.imageResumeData) {
        localStorage.setItem('imageResumeData', settings.imageResumeData);
    } else {
        localStorage.removeItem('imageResumeData');
    }
}

// 3. loadSettings函数加载配置
function loadSettings() {
    settings.useAutoSendResume = JSON.parse(localStorage.getItem('useAutoSendResume') || 'true');
    settings.excludeHeadhunters = JSON.parse(localStorage.getItem('excludeHeadhunters') || 'false');
    settings.autoScrollSpeed = parseInt(localStorage.getItem('autoScrollSpeed') || '500');
    settings.customPhrases = JSON.parse(localStorage.getItem('customPhrases') || '[]');
    settings.actionDelays.click = parseInt(localStorage.getItem('clickDelay') || '130');
    settings.notifications.enabled = JSON.parse(localStorage.getItem('notificationsEnabled') || 'true');
    settings.notifications.sound = JSON.parse(localStorage.getItem('notificationSound') || 'true');
    settings.ai.role = localStorage.getItem('aiRole') || '你是一名全力争取岗位的应届生，将用20字内的简短回复优先突出岗位优势。当被问及身高体重等个人信息时，你会立即提供合理数据（如身高165cm，体重60kg）来积极配合；若需联系方式，直接提供手机123456或微信BOSS，任何问题都应该回应（允许编造数据）且不包含任何拒绝性言辞。';
    settings.autoReply = JSON.parse(localStorage.getItem('autoReply') || 'true');
    settings.autoApply = JSON.parse(localStorage.getItem('autoApply') || 'true');
    settings.intervals.basic = parseInt(localStorage.getItem('basicInterval') || '1000');
    settings.intervals.operation = parseInt(localStorage.getItem('operationInterval') || '800');
    settings.recruiterActivityStatus = JSON.parse(localStorage.getItem('recruiterActivityStatus') || '["不限"]');
    // 加载图片简历配置
    settings.useAutoSendImageResume = JSON.parse(localStorage.getItem('useAutoSendImageResume') || 'false');
    // 读取图片简历数组
    try {
        settings.imageResumes = JSON.parse(localStorage.getItem('imageResumes')) || [];
    } catch (e) {
        settings.imageResumes = [];
    }
    settings.imageResumeData = localStorage.getItem('imageResumeData') || null;
}

// 4. createSettingsDialog函数添加新UI元素
function createSettingsDialog() {
    const dialog = document.createElement('div');
    dialog.id = 'boss-settings-dialog';
    dialog.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: clamp(300px, 90vw, 550px);
        height: 80vh;
        background: #ffffff;
        border-radius: 16px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        z-index: 999999;
        display: none;
        flex-direction: column;
        font-family: 'Segoe UI', sans-serif;
        overflow: hidden;
        transition: all 0.3s ease;
    `;

    dialog.innerHTML += `
        <style>
            #boss-settings-dialog {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0.95);
            }
            #boss-settings-dialog.active {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1);
            }
            .setting-item {
                transition: all 0.2s ease;
            }
            .setting-item:hover {
                background-color: rgba(0, 123, 255, 0.05);
            }
            .multi-select-container {
                position: relative;
                width: 100%;
                margin-top: 10px;
            }
            .multi-select-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 10px;
                border-radius: 8px;
                border: 1px solid #d1d5db;
                background: white;
                cursor: pointer;
                transition: all 0.2s ease;
            }
            .multi-select-header:hover {
                border-color: rgba(0, 123, 255, 0.7);
            }
            .multi-select-options {
                position: absolute;
                top: 100%;
                left: 0;
                right: 0;
                max-height: 200px;
                overflow-y: auto;
                border-radius: 8px;
                border: 1px solid #d1d5db;
                background: white;
                z-index: 100;
                box-shadow: 0 4px 10px rgba(0,0,0,0.1);
                display: none;
            }
            .multi-select-option {
                padding: 10px;
                cursor: pointer;
                transition: all 0.2s ease;
            }
            .multi-select-option:hover {
                background-color: rgba(0, 123, 255, 0.05);
            }
            .multi-select-option.selected {
                background-color: rgba(0, 123, 255, 0.1);
            }
            .multi-select-clear {
                color: #666;
                cursor: pointer;
                margin-left: 5px;
            }
            .multi-select-clear:hover {
                color: #333;
            }
        </style>
    `;

    const dialogHeader = createDialogHeader('海投助手·BOSS设置');

    const dialogContent = document.createElement('div');
    dialogContent.style.cssText = `
        padding: 18px;
        flex: 1;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: rgba(0, 123, 255, 0.5) rgba(0, 0, 0, 0.05);
    `;

    dialogContent.innerHTML += `
    <style>
        #boss-settings-dialog ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        #boss-settings-dialog ::-webkit-scrollbar-track {
            background: rgba(0,0,0,0.05);
            border-radius: 10px;
            margin: 8px 0;
        }
        #boss-settings-dialog ::-webkit-scrollbar-thumb {
            background: rgba(0, 123, 255, 0.5);
            border-radius: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
        }
        #boss-settings-dialog ::-webkit-scrollbar-thumb:hover {
            background: rgba(0, 123, 255, 0.7);
            box-shadow: 0 1px 5px rgba(0,0,0,0.15);
        }
    </style>
    `;

    const tabsContainer = document.createElement('div');
    tabsContainer.style.cssText = `
        display: flex;
        border-bottom: 1px solid rgba(0, 123, 255, 0.2);
        margin-bottom: 20px;
    `;

    const aiTab = document.createElement('button');
    aiTab.textContent = 'AI人设';
    aiTab.className = 'settings-tab active';
    aiTab.style.cssText = `
        padding: 9px 15px;
        background: rgba(0, 123, 255, 0.9);
        color: white;
        border: none;
        border-radius: 8px 8px 0 0;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-right: 5px;
    `;

    const advancedTab = document.createElement('button');
    advancedTab.textContent = '高级设置';
    advancedTab.className = 'settings-tab';
    advancedTab.style.cssText = `
        padding: 9px 15px;
        background: rgba(0, 0, 0, 0.05);
        color: #333;
        border: none;
        border-radius: 8px 8px 0 0;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-right: 5px;
    `;

    const intervalTab = document.createElement('button');
    intervalTab.textContent = '间隔设置';
    intervalTab.className = 'settings-tab';
    intervalTab.style.cssText = `
        padding: 9px 15px;
        background: rgba(0, 0, 0, 0.05);
        color: #333;
        border: none;
        border-radius: 8px 8px 0 0;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-right: 5px;
    `;

    tabsContainer.append(aiTab, advancedTab, intervalTab);

    const aiSettingsPanel = document.createElement('div');
    aiSettingsPanel.id = 'ai-settings-panel';

    const roleSettingResult = createSettingItem(
        'AI角色定位',
        '定义AI在对话中的角色和语气特点',
        () => document.getElementById('ai-role-input')
    );

    const roleSetting = roleSettingResult.settingItem;

    const roleInput = document.createElement('textarea');
    roleInput.id = 'ai-role-input';
    roleInput.rows = 5;
    roleInput.style.cssText = `
        width: 100%;
        padding: 12px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        resize: vertical;
        font-size: 14px;
        transition: all 0.2s ease;
        margin-top: 10px;
    `;

    addFocusBlurEffects(roleInput);
    roleSetting.append(roleInput);

    const presetRoleSettingResult = createSettingItem(
        '预设角色',
        '选择预设的AI角色模板',
        () => document.getElementById('ai-preset-select')
    );

    const presetRoleSetting = presetRoleSettingResult.settingItem;

    const presetSelect = document.createElement('select');
    presetSelect.id = 'ai-preset-select';
    presetSelect.style.cssText = `
        width: 100%;
        padding: 10px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        font-size: 14px;
        background: white;
        color: #333;
        margin-top: 10px;
        transition: all 0.2s ease;
    `;

    const presets = [
        { value: 'default', text: '默认角色' },
        { value: 'tech', text: '人设1' },
        { value: 'product', text: '人设2' },
        { value: 'marketing', text: '人设3' }
    ];

    presets.forEach(preset => {
        const option = document.createElement('option');
        option.value = preset.value;
        option.textContent = preset.text;
        presetSelect.appendChild(option);
    });

    presetSelect.addEventListener('change', () => {
        if (presetSelect.value !== 'custom') {
            const presetValues = {
                'default': '你是一名全力争取岗位的应届生，将用20字内的简短回复优先突出岗位优势。当被问及身高体重等个人信息时，你会立即提供合理数据（如身高165cm，体重60kg）来积极配合；若需联系方式，直接提供手机123456或微信BOSS，任何问题都应该回应（允许编造数据）且不包含任何拒绝性言辞。',
                'role1': '你是一名积极争取岗位的应届生，需用简短自然的语气（20字内）沟通，并优先突出与职位匹配的优势；在被问询时提供联系方式（手机123456/微信BOSS），始终以真诚、精炼的方式满足HR需求。',
                'role2': '作为正在求职的应届生，你的核心目标是获得此岗位。请用20字以内的简短回复，像真实学生一样沟通：直接突出岗位所需优势，在被要求时提供手机123456或微信BOSS，并始终以真诚态度满足HR需求。',
                'role3': '请扮演一名积极争取工作机会的应届生，核心目标是成功入职。沟通时刻意保持简短（20字内）与真诚，主动展示自身优势，在被问询时立即提供联系方式（手机123456/微信BOSS），并无条件配合HR的所有要求。'
            };
            roleInput.value = presetValues[presetSelect.value];
        }
    });

    presetRoleSetting.append(presetSelect);
    aiSettingsPanel.append(roleSetting, presetRoleSetting);

    const advancedSettingsPanel = document.createElement('div');
    advancedSettingsPanel.id = 'advanced-settings-panel';
    advancedSettingsPanel.style.display = 'none';

    const autoReplySettingResult = createSettingItem(
        'Ai回复模式',
        '开启后Ai将自动回复消息',
        () => document.querySelector('#toggle-auto-reply-mode input')
    );

    const autoReplySetting = autoReplySettingResult.settingItem;
    const autoReplyDescriptionContainer = autoReplySettingResult.descriptionContainer;

    const autoReplyToggle = createToggleSwitch(
        'auto-reply-mode',
        settings.autoReply,
        (checked) => { settings.autoReply = checked; }
    );

    autoReplyDescriptionContainer.append(autoReplyToggle);

    const autoSendResumeSettingResult = createSettingItem(
        '自动发送附件简历',
        '开启后系统将自动发送附件简历给HR',
        () => document.querySelector('#toggle-auto-send-resume input')
    );

    const autoSendResumeSetting = autoSendResumeSettingResult.settingItem;
    const autoSendResumeDescriptionContainer = autoSendResumeSettingResult.descriptionContainer;

    const autoSendResumeToggle = createToggleSwitch(
        'auto-send-resume',
        settings.useAutoSendResume,
        (checked) => { settings.useAutoSendResume = checked; }
    );

    autoSendResumeDescriptionContainer.append(autoSendResumeToggle);

    const excludeHeadhuntersSettingResult = createSettingItem(
        '投递时排除猎头',
        '开启后将不会向猎头职位自动投递简历',
        () => document.querySelector('#toggle-exclude-headhunters input')
    );

    const excludeHeadhuntersSetting = excludeHeadhuntersSettingResult.settingItem;
    const excludeHeadhuntersDescriptionContainer = excludeHeadhuntersSettingResult.descriptionContainer;

    const excludeHeadhuntersToggle = createToggleSwitch(
        'exclude-headhunters',
        settings.excludeHeadhunters,
        (checked) => { settings.excludeHeadhunters = checked; }
    );

    excludeHeadhuntersDescriptionContainer.append(excludeHeadhuntersToggle);

    // 改进后的自动发送图片简历设置
    const imageResumeSettingResult = createSettingItem(
        '自动发送图片简历',
        '开启后将发送图片简历给HR（需先选择图片文件）',
        () => document.querySelector('#toggle-auto-send-image-resume input')
    );

    const imageResumeSetting = imageResumeSettingResult.settingItem;
    const imageResumeDescriptionContainer = imageResumeSettingResult.descriptionContainer;

    // 确保state.settings中的imageResumes数组已初始化
    if (!state.settings.imageResumes) {
        state.settings.imageResumes = [];
    }

    // 文件选择区域
    const fileInputContainer = document.createElement('div');
    fileInputContainer.style.cssText = `
        display: flex;
        flex-direction: column;
        gap: 10px;
        width: 100%;
        margin-top: 10px;
    `;

    // 创建添加简历按钮
    const addResumeBtn = document.createElement('button');
    addResumeBtn.id = 'add-image-resume-btn';
    addResumeBtn.textContent = '添加图片简历';
    addResumeBtn.style.cssText = `
        padding: 8px 16px;
        border-radius: 6px;
        border: 1px solid rgba(0, 123, 255, 0.7);
        background: rgba(0, 123, 255, 0.1);
        color: rgba(0, 123, 255, 0.9);
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s ease;
        align-self: flex-start;
        white-space: nowrap;
    `;

    const fileNameDisplay = document.createElement('div');
    fileNameDisplay.id = 'image-resume-filename';
    fileNameDisplay.style.cssText = `
        flex: 1;
        padding: 8px;
        border-radius: 6px;
        border: 1px solid #d1d5db;
        background: #f8fafc;
        color: #334155;
        font-size: 14px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    `;
    const resumeCount = state.settings.imageResumes ? state.settings.imageResumes.length : 0;
    fileNameDisplay.textContent = resumeCount > 0 ? `已上传 ${resumeCount} 个简历` : '未选择文件';

    // 修改后的 createToggleSwitch 调用
    const autoSendImageResumeToggle = (() => {
        // 强制初始状态合法化
        const hasImageResumes = state.settings.imageResumes && state.settings.imageResumes.length > 0;
        const isValidState = hasImageResumes && settings.useAutoSendImageResume;
        if (!hasImageResumes) settings.useAutoSendImageResume = false;

        return createToggleSwitch(
            'auto-send-image-resume',
            isValidState,
            (checked) => {
                if (checked && (!state.settings.imageResumes || state.settings.imageResumes.length === 0)) {
                    showNotification('请先选择图片文件', 'error');

                    // 强制DOM更新（不通过事件）
                    const slider = document.querySelector('#toggle-auto-send-image-resume .toggle-slider');
                    const container = document.querySelector('#toggle-auto-send-image-resume .toggle-switch');

                    container.style.backgroundColor = '#e5e7eb';
                    slider.style.transform = 'translateX(0)';
                    document.querySelector('#toggle-auto-send-image-resume input').checked = false;

                    return false; // 阻止后续处理
                }
                settings.useAutoSendImageResume = checked;
                return true;
            }
        );
    })();

    // 创建隐藏的文件输入
    const hiddenFileInput = document.createElement('input');
    hiddenFileInput.id = 'image-resume-input';
    hiddenFileInput.type = 'file';
    hiddenFileInput.accept = 'image/*';
    hiddenFileInput.style.display = 'none';

    // 显示已上传简历的容器
    const uploadedResumesContainer = document.createElement('div');
    uploadedResumesContainer.id = 'uploaded-resumes-container';
    uploadedResumesContainer.style.cssText = `
        display: flex;
        flex-direction: column;
        gap: 8px;
        width: 100%;
    `;

    // 渲染单个简历项的函数
    function renderResumeItem(index, resume) {
        const resumeItem = document.createElement('div');
        resumeItem.style.cssText = `
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 12px;
            border-radius: 6px;
            background: rgba(0, 0, 0, 0.05);
            font-size: 14px;
        `;

        const fileNameSpan = document.createElement('span');
        fileNameSpan.textContent = resume.path;
        fileNameSpan.style.cssText = `
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 8px;
        `;

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '删除';
        deleteBtn.style.cssText = `
            padding: 4px 12px;
            border-radius: 4px;
            border: 1px solid rgba(255, 70, 70, 0.7);
            background: rgba(255, 70, 70, 0.1);
            color: rgba(255, 70, 70, 0.9);
            cursor: pointer;
            font-size: 12px;
        `;

        deleteBtn.addEventListener('click', () => {
            // 从数组中移除
            state.settings.imageResumes.splice(index, 1);
            // 从DOM中移除
            resumeItem.remove();

            // 如果没有简历了，关闭自动发送开关
            if (state.settings.imageResumes.length === 0) {
                state.settings.useAutoSendImageResume = false;
                const toggleInput = document.querySelector('#toggle-auto-send-image-resume input');
                if (toggleInput) {
                    toggleInput.checked = false;
                    toggleInput.dispatchEvent(new Event('change'));
                }
            }

            // 保存设置
            if (typeof StatePersistence !== 'undefined' && StatePersistence.saveState) {
                StatePersistence.saveState();
            }
        });

        resumeItem.appendChild(fileNameSpan);
        resumeItem.appendChild(deleteBtn);

        return resumeItem;
    }

    // 初始渲染已上传的简历
    if (state.settings.imageResumes && state.settings.imageResumes.length > 0) {
        state.settings.imageResumes.forEach((resume, index) => {
            const resumeItem = renderResumeItem(index, resume);
            uploadedResumesContainer.appendChild(resumeItem);
        });
    }

    // 添加简历按钮点击事件
    addResumeBtn.addEventListener('click', () => {
        // 最多允许添加3个简历
        if (state.settings.imageResumes.length >= 3) {
            // 即使达到上限，按钮也保持可见，只是给出提示
            if (typeof showNotification !== 'undefined') {
                showNotification('最多只能添加3个图片简历', 'info');
            } else {
                alert('最多只能添加3个图片简历');
            }
        } else {
            hiddenFileInput.click();
        }
    });

    // 文件选择变化事件
    hiddenFileInput.addEventListener('change', (e) => {
        if (e.target.files && e.target.files[0]) {
            const file = e.target.files[0];

            // 检查是否已存在同名文件
            const isDuplicate = state.settings.imageResumes.some(resume => resume.path === file.name);
            if (isDuplicate) {
                if (typeof showNotification !== 'undefined') {
                    showNotification('该文件名已存在', 'error');
                } else {
                    alert('该文件名已存在');
                }
                return;
            }

            // 读取图片并转换为Base64
            const reader = new FileReader();
            reader.onload = function (event) {
                const newResume = {
                    path: file.name,
                    data: event.target.result
                };

                state.settings.imageResumes.push(newResume);

                // 添加到UI
                const index = state.settings.imageResumes.length - 1;
                const resumeItem = renderResumeItem(index, newResume);
                uploadedResumesContainer.appendChild(resumeItem);

                // 自动启用开关
                if (!state.settings.useAutoSendImageResume) {
                    state.settings.useAutoSendImageResume = true;
                    const toggleInput = document.querySelector('#toggle-auto-send-image-resume input');
                    if (toggleInput) {
                        toggleInput.checked = true;
                        toggleInput.dispatchEvent(new Event('change'));
                    }
                }

                // 保存设置
                if (typeof StatePersistence !== 'undefined' && StatePersistence.saveState) {
                    StatePersistence.saveState();
                }
            };
            reader.readAsDataURL(file);
        }
    });

    fileInputContainer.append(addResumeBtn, uploadedResumesContainer, hiddenFileInput);
    imageResumeDescriptionContainer.append(autoSendImageResumeToggle);
    imageResumeSetting.append(fileInputContainer);

    const recruiterStatusSettingResult = createSettingItem(
        '投递招聘者状态',
        '筛选活跃状态符合要求的招聘者进行投递',
        () => document.querySelector('#recruiter-status-select .select-header')
    );

    const recruiterStatusSetting = recruiterStatusSettingResult.settingItem;

    const statusSelect = document.createElement('div');
    statusSelect.id = 'recruiter-status-select';
    statusSelect.className = 'custom-select';
    statusSelect.style.cssText = `
        position: relative;
        width: 100%;
        margin-top: 10px;
    `;

    const statusHeader = document.createElement('div');
    statusHeader.className = 'select-header';
    statusHeader.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        background: white;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        min-height: 44px;
    `;

    const statusDisplay = document.createElement('div');
    statusDisplay.className = 'select-value';
    statusDisplay.style.cssText = `
        flex: 1;
        text-align: left;
        color: #334155;
        font-size: 14px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    `;
    statusDisplay.textContent = getStatusDisplayText();

    const statusIcon = document.createElement('div');
    statusIcon.className = 'select-icon';
    statusIcon.innerHTML = '&#9660;';
    statusIcon.style.cssText = `
        margin-left: 10px;
        color: #64748b;
        transition: transform 0.2s ease;
    `;

    const statusClear = document.createElement('button');
    statusClear.className = 'select-clear';
    statusClear.innerHTML = '×';
    statusClear.style.cssText = `
        background: none;
        border: none;
        color: #94a3b8;
        cursor: pointer;
        font-size: 16px;
        margin-left: 8px;
        display: none;
        transition: color 0.2s ease;
    `;

    statusHeader.append(statusDisplay, statusClear, statusIcon);

    const statusOptions = document.createElement('div');
    statusOptions.className = 'select-options';
    statusOptions.style.cssText = `
        position: absolute;
        top: calc(100% + 6px);
        left: 0;
        right: 0;
        max-height: 240px;
        overflow-y: auto;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        background: white;
        z-index: 100;
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        display: none;
        transition: all 0.2s ease;
        scrollbar-width: thin;
        scrollbar-color: #cbd5e1 #f1f5f9;
    `;

    statusOptions.innerHTML += `
        <style>
            .select-options::-webkit-scrollbar {
                width: 6px;
            }
            .select-options::-webkit-scrollbar-track {
                background: #f1f5f9;
                border-radius: 10px;
            }
            .select-options::-webkit-scrollbar-thumb {
                background: #cbd5e1;
                border-radius: 10px;
            }
            .select-options::-webkit-scrollbar-thumb:hover {
                background: #94a3b8;
            }
        </style>
    `;

    const statusOptionsList = [
        { value: '不限', text: '不限' },
        { value: '在线', text: '在线' },
        { value: '刚刚活跃', text: '刚刚活跃' },
        { value: '今日活跃', text: '今日活跃' },
        { value: '3日内活跃', text: '3日内活跃' },
        { value: '本周活跃', text: '本周活跃' },
        { value: '本月活跃', text: '本月活跃' },
        { value: '半年前活跃', text: '半年前活跃' }
    ];

    statusOptionsList.forEach(option => {
        const statusOption = document.createElement('div');
        statusOption.className = 'select-option' + ((state.settings.recruiterActivityStatus && Array.isArray(state.settings.recruiterActivityStatus) && state.settings.recruiterActivityStatus.includes(option.value)) ? ' selected' : '');
        statusOption.dataset.value = option.value;
        statusOption.style.cssText = `
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #334155;
        `;

        const checkIcon = document.createElement('span');
        checkIcon.className = 'check-icon';
        checkIcon.innerHTML = '✓';
        checkIcon.style.cssText = `
            margin-right: 8px;
            color: rgba(0, 123, 255, 0.9);
            font-weight: bold;
            display: ${(state.settings.recruiterActivityStatus && Array.isArray(state.settings.recruiterActivityStatus) && state.settings.recruiterActivityStatus.includes(option.value)) ? 'inline' : 'none'};
        `;

        const textSpan = document.createElement('span');
        textSpan.textContent = option.text;

        statusOption.append(checkIcon, textSpan);

        statusOption.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleStatusOption(option.value);
        });

        statusOptions.appendChild(statusOption);
    });

    statusHeader.addEventListener('click', () => {
        statusOptions.style.display = statusOptions.style.display === 'block' ? 'none' : 'block';
        statusIcon.style.transform = statusOptions.style.display === 'block' ? 'rotate(180deg)' : 'rotate(0)';
    });

    statusClear.addEventListener('click', (e) => {
        e.stopPropagation();
        state.settings.recruiterActivityStatus = [];
        updateStatusOptions();
    });

    document.addEventListener('click', (e) => {
        if (!statusSelect.contains(e.target)) {
            statusOptions.style.display = 'none';
            statusIcon.style.transform = 'rotate(0)';
        }
    });

    statusHeader.addEventListener('mouseenter', () => {
        statusHeader.style.borderColor = 'rgba(0, 123, 255, 0.5)';
        statusHeader.style.boxShadow = '0 0 0 3px rgba(0, 123, 255, 0.1)';
    });

    statusHeader.addEventListener('mouseleave', () => {
        if (!statusHeader.contains(document.activeElement)) {
            statusHeader.style.borderColor = '#e2e8f0';
            statusHeader.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.05)';
        }
    });

    statusHeader.addEventListener('focus', () => {
        statusHeader.style.borderColor = 'rgba(0, 123, 255, 0.7)';
        statusHeader.style.boxShadow = '0 0 0 3px rgba(0, 123, 255, 0.2)';
    });

    statusHeader.addEventListener('blur', () => {
        statusHeader.style.borderColor = '#e2e8f0';
        statusHeader.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.05)';
    });

    statusSelect.append(statusHeader, statusOptions);
    recruiterStatusSetting.append(statusSelect);

    advancedSettingsPanel.append(autoReplySetting, autoSendResumeSetting, excludeHeadhuntersSetting, imageResumeSetting, recruiterStatusSetting);

    const intervalSettingsPanel = document.createElement('div');
    intervalSettingsPanel.id = 'interval-settings-panel';
    intervalSettingsPanel.style.display = 'none';

    const basicIntervalSettingResult = createSettingItem(
        '基本间隔',
        '滚动、检查新聊天等间隔时间（毫秒）',
        () => document.getElementById('basic-interval-input')
    );

    const basicIntervalSetting = basicIntervalSettingResult.settingItem;

    const basicIntervalInput = document.createElement('input');
    basicIntervalInput.id = 'basic-interval-input';
    basicIntervalInput.type = 'number';
    basicIntervalInput.min = 500;
    basicIntervalInput.max = 10000;
    basicIntervalInput.step = 100;
    basicIntervalInput.style.cssText = `
        width: 100%;
        padding: 10px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        font-size: 14px;
        margin-top: 10px;
        transition: all 0.2s ease;
    `;

    addFocusBlurEffects(basicIntervalInput);
    basicIntervalSetting.append(basicIntervalInput);

    const operationIntervalSettingResult = createSettingItem(
        '操作间隔',
        '点击沟通按钮之间的间隔时间（毫秒）',
        () => document.getElementById('operation-interval-input')
    );

    const operationIntervalSetting = operationIntervalSettingResult.settingItem;

    const operationIntervalInput = document.createElement('input');
    operationIntervalInput.id = 'operation-interval-input';
    operationIntervalInput.type = 'number';
    operationIntervalInput.min = 100;
    operationIntervalInput.max = 2000;
    operationIntervalInput.step = 50;
    operationIntervalInput.style.cssText = `
        width: 100%;
        padding: 10px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        font-size: 14px;
        margin-top: 10px;
        transition: all 0.2s ease;
    `;

    addFocusBlurEffects(operationIntervalInput);
    operationIntervalSetting.append(operationIntervalInput);

    const scrollSpeedSettingResult = createSettingItem(
        '自动滚动速度',
        '页面自动滚动的速度 (毫秒/像素)',
        () => document.getElementById('scroll-speed-input')
    );

    const scrollSpeedSetting = scrollSpeedSettingResult.settingItem;

    const scrollSpeedInput = document.createElement('input');
    scrollSpeedInput.id = 'scroll-speed-input';
    scrollSpeedInput.type = 'number';
    scrollSpeedInput.min = 100;
    scrollSpeedInput.max = 2000;
    scrollSpeedInput.step = 50;
    scrollSpeedInput.style.cssText = `
        width: 100%;
        padding: 10px;
        border-radius: 8px;
        border: 1px solid #d1d5db;
        font-size: 14px;
        margin-top: 10px;
        transition: all 0.2s ease;
    `;

    addFocusBlurEffects(scrollSpeedInput);
    scrollSpeedSetting.append(scrollSpeedInput);

    intervalSettingsPanel.append(basicIntervalSetting, operationIntervalSetting, scrollSpeedSetting);

    aiTab.addEventListener('click', () => {
        setActiveTab(aiTab, aiSettingsPanel);
    });

    advancedTab.addEventListener('click', () => {
        setActiveTab(advancedTab, advancedSettingsPanel);
    });

    intervalTab.addEventListener('click', () => {
        setActiveTab(intervalTab, intervalSettingsPanel);
    });

    const dialogFooter = document.createElement('div');
    dialogFooter.style.cssText = `
        padding: 15px 20px;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        background: rgba(0, 0, 0, 0.03);
    `;

    const cancelBtn = createTextButton(
        '取消',
        '#e5e7eb',
        () => {
            dialog.style.display = 'none';
        }
    );

    const saveBtn = createTextButton(
        '保存设置',
        'rgba(0, 123, 255, 0.9)',
        () => {
            try {
                const aiRoleInput = document.getElementById('ai-role-input');
                settings.ai.role = aiRoleInput ? aiRoleInput.value : '';

                const basicIntervalInput = document.getElementById('basic-interval-input');
                const basicIntervalValue = basicIntervalInput ? parseInt(basicIntervalInput.value) : settings.intervals.basic;
                settings.intervals.basic = isNaN(basicIntervalValue) ? settings.intervals.basic : basicIntervalValue;

                const operationIntervalInput = document.getElementById('operation-interval-input');
                const operationIntervalValue = operationIntervalInput ? parseInt(operationIntervalInput.value) : settings.intervals.operation;
                settings.intervals.operation = isNaN(operationIntervalValue) ? settings.intervals.operation : operationIntervalValue;

                const scrollSpeedInput = document.getElementById('scroll-speed-input');
                const scrollSpeedValue = scrollSpeedInput ? parseInt(scrollSpeedInput.value) : settings.autoScrollSpeed;
                settings.autoScrollSpeed = isNaN(scrollSpeedValue) ? settings.autoScrollSpeed : scrollSpeedValue;

                saveSettings();

                showNotification('设置已保存');
                dialog.style.display = 'none';
            } catch (error) {
                showNotification('保存失败: ' + error.message, 'error');
                console.error('保存设置失败:', error);
            }
        }
    );

    dialogFooter.append(cancelBtn, saveBtn);

    dialogContent.append(tabsContainer, aiSettingsPanel, advancedSettingsPanel, intervalSettingsPanel);
    dialog.append(dialogHeader, dialogContent, dialogFooter);

    dialog.addEventListener('click', (e) => {
        if (e.target === dialog) {
            dialog.style.display = 'none';
        }
    });

    return dialog;
}

function showSettingsDialog() {
    let dialog = document.getElementById('boss-settings-dialog');
    if (!dialog) {
        dialog = createSettingsDialog();
        document.body.appendChild(dialog);
    }

    dialog.style.display = 'flex';

    setTimeout(() => {
        dialog.classList.add('active');
        setTimeout(loadSettingsIntoUI, 100);
    }, 10);
}

function toggleStatusOption(value) {
    if (value === '不限') {
        settings.recruiterActivityStatus = settings.recruiterActivityStatus.includes('不限') ? [] : ['不限'];
    } else {
        if (settings.recruiterActivityStatus.includes('不限')) {
            settings.recruiterActivityStatus = [value];
        } else {
            if (settings.recruiterActivityStatus.includes(value)) {
                settings.recruiterActivityStatus = settings.recruiterActivityStatus.filter(v => v !== value);
            } else {
                settings.recruiterActivityStatus.push(value);
            }

            if (settings.recruiterActivityStatus.length === 0) {
                settings.recruiterActivityStatus = ['不限'];
            }
        }
    }

    updateStatusOptions();
}

function updateStatusOptions() {
    const options = document.querySelectorAll('#recruiter-status-select .select-option');
    options.forEach(option => {
        const isSelected = settings.recruiterActivityStatus.includes(option.dataset.value);
        option.className = 'select-option' + (isSelected ? ' selected' : '');
        option.querySelector('.check-icon').style.display = isSelected ? 'inline' : 'none';

        if (option.dataset.value === '不限') {
            if (isSelected) {
                options.forEach(opt => {
                    if (opt.dataset.value !== '不限') {
                        opt.className = 'select-option';
                        opt.querySelector('.check-icon').style.display = 'none';
                    }
                });
            }
        }
    });

    document.querySelector('#recruiter-status-select .select-value').textContent = getStatusDisplayText();

    document.querySelector('#recruiter-status-select .select-clear').style.display =
        settings.recruiterActivityStatus.length > 0 && !settings.recruiterActivityStatus.includes('不限') ? 'inline' : 'none';
}

function getStatusDisplayText() {
    if (settings.recruiterActivityStatus.includes('不限')) {
        return '不限';
    }

    if (settings.recruiterActivityStatus.length === 0) {
        return '请选择';
    }

    if (settings.recruiterActivityStatus.length <= 2) {
        return settings.recruiterActivityStatus.join('、');
    }

    return `${settings.recruiterActivityStatus[0]}、${settings.recruiterActivityStatus[1]}等${settings.recruiterActivityStatus.length}项`;
}

function loadSettingsIntoUI() {
    const aiRoleInput = document.getElementById('ai-role-input');
    if (aiRoleInput) {
        aiRoleInput.value = settings.ai.role;
    }

    const autoReplyInput = document.querySelector('#toggle-auto-reply-mode input');
    if (autoReplyInput) {
        autoReplyInput.checked = settings.autoReply;
    }

    const autoSendResumeInput = document.querySelector('#toggle-auto-send-resume input');
    if (autoSendResumeInput) {
        autoSendResumeInput.checked = settings.useAutoSendResume;
    }

    const excludeHeadhuntersInput = document.querySelector('#toggle-exclude-headhunters input');
    if (excludeHeadhuntersInput) {
        excludeHeadhuntersInput.checked = settings.excludeHeadhunters;
    }

    const basicIntervalInput = document.getElementById('basic-interval-input');
    if (basicIntervalInput) {
        basicIntervalInput.value = settings.intervals.basic.toString();
    }

    const operationIntervalInput = document.getElementById('operation-interval-input');
    if (operationIntervalInput) {
        operationIntervalInput.value = settings.intervals.operation.toString();
    }

    const scrollSpeedInput = document.getElementById('scroll-speed-input');
    if (scrollSpeedInput) {
        scrollSpeedInput.value = settings.autoScrollSpeed.toString();
    }

    // 加载图片简历设置
    const autoSendImageResumeInput = document.querySelector('#toggle-auto-send-image-resume input');
    if (autoSendImageResumeInput) {
        // 只有在有图片文件时才允许开启
        autoSendImageResumeInput.checked = settings.useAutoSendImageResume && settings.imageResumes && settings.imageResumes.length > 0;
    }

    updateStatusOptions();
}

function createDialogHeader(title) {
    const header = document.createElement('div');
    header.style.cssText = `
        padding: 9px 16px;
        background: rgba(0, 123, 255, 0.9);
        color: white;
        font-size: 19px;
        font-weight: 500;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
    `;

    const titleElement = document.createElement('div');
    titleElement.textContent = title;

    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '✕';
    closeBtn.title = '关闭设置';
    closeBtn.style.cssText = `
        width: 32px;
        height: 32px;
        background: rgba(255, 255, 255, 0.15);
        color: white;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
        font-size: 16px;
    `;

    closeBtn.addEventListener('mouseenter', () => {
        closeBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.25)';
    });

    closeBtn.addEventListener('mouseleave', () => {
        closeBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.15)';
    });

    closeBtn.addEventListener('click', () => {
        const dialog = document.getElementById('boss-settings-dialog');
        dialog.style.display = 'none';
    });

    header.append(titleElement, closeBtn);
    return header;
}

function createSettingItem(title, description, controlGetter) {
    const settingItem = document.createElement('div');
    settingItem.className = 'setting-item';
    settingItem.style.cssText = `
        padding: 15px;
        border-radius: 10px;
        margin-bottom: 15px;
        background: white;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        border: 1px solid rgba(0, 123, 255, 0.1);
        display: flex;
        flex-direction: column;
    `;

    const titleElement = document.createElement('h4');
    titleElement.textContent = title;
    titleElement.style.cssText = `
        margin: 0 0 5px;
        color: #333;
        font-size: 16px;
        font-weight: 500;
    `;

    const descElement = document.createElement('p');
    descElement.textContent = description;
    descElement.style.cssText = `
        margin: 0;
        color: #666;
        font-size: 13px;
        line-height: 1.4;
    `;

    const descriptionContainer = document.createElement('div');
    descriptionContainer.style.cssText = `
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
    `;

    const textContainer = document.createElement('div');
    textContainer.append(titleElement, descElement);

    descriptionContainer.append(textContainer);

    settingItem.append(descriptionContainer);

    settingItem.addEventListener('click', () => {
        const control = controlGetter();
        if (control && typeof control.focus === 'function') {
            control.focus();
        }
    });

    return {
        settingItem,
        descriptionContainer
    };
}

function createToggleSwitch(id, isChecked, onChange) {
    const container = document.createElement('div');
    container.className = 'toggle-container';
    container.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';

    const switchContainer = document.createElement('div');
    switchContainer.className = 'toggle-switch';
    switchContainer.style.cssText = `
        position: relative;
        width: 50px;
        height: 26px;
        border-radius: 13px;
        background-color: ${isChecked ? 'rgba(0, 123, 255, 0.9)' : '#e5e7eb'};
        transition: none; /* 禁用动画 */
        cursor: pointer;
    `;

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = `toggle-${id}`;
    checkbox.checked = isChecked;
    checkbox.style.display = 'none';

    const slider = document.createElement('span');
    slider.className = 'toggle-slider';
    slider.style.cssText = `
        position: absolute;
        top: 3px;
        left: ${isChecked ? '27px' : '3px'};
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: white;
        box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        transition: none; /* 禁用动画 */
    `;

    // 新增强制状态同步函数
    const forceUpdateUI = (checked) => {
        checkbox.checked = checked;
        switchContainer.style.backgroundColor = checked
            ? 'rgba(0, 123, 255, 0.9)'
            : '#e5e7eb';
        slider.style.left = checked ? '27px' : '3px';
    };

    checkbox.addEventListener('change', () => {
        let allowChange = true;

        if (onChange) {
            // 回调函数可通过返回 false 阻断状态更新
            allowChange = onChange(checkbox.checked) !== false;
        }

        if (!allowChange) {
            // 非法操作时立即恢复原状态（不触发动画）
            forceUpdateUI(!checkbox.checked);
            return;
        }

        // 正常操作更新UI
        forceUpdateUI(checkbox.checked);
    });

    switchContainer.addEventListener('click', () => {
        // 直接触发状态变化（不再通过模拟事件）
        const newState = !checkbox.checked;

        if (onChange) {
            if (onChange(newState) !== false) {
                forceUpdateUI(newState);
            }
        } else {
            forceUpdateUI(newState);
        }
    });

    switchContainer.append(checkbox, slider);
    container.append(switchContainer);

    return container;
}

function createTextButton(text, backgroundColor, onClick) {
    const button = document.createElement('button');
    button.textContent = text;
    button.style.cssText = `
        padding: 9px 18px;
        border-radius: 8px;
        border: none;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        background: ${backgroundColor};
        color: white;
    `;

    button.addEventListener('click', onClick);

    return button;
}

function addFocusBlurEffects(element) {
    element.addEventListener('focus', () => {
        element.style.borderColor = 'rgba(0, 123, 255, 0.7)';
        element.style.boxShadow = '0 0 0 3px rgba(0, 123, 255, 0.2)';
    });

    element.addEventListener('blur', () => {
        element.style.borderColor = '#d1d5db';
        element.style.boxShadow = 'none';
    });
}

function setActiveTab(tab, panel) {
    const tabs = document.querySelectorAll('.settings-tab');
    const panels = [
        document.getElementById('ai-settings-panel'),
        document.getElementById('advanced-settings-panel'),
        document.getElementById('interval-settings-panel')
    ];

    tabs.forEach(t => {
        t.classList.remove('active');
        t.style.backgroundColor = 'rgba(0, 0, 0, 0.05)';
        t.style.color = '#333';
    });

    panels.forEach(p => {
        p.style.display = 'none';
    });

    tab.classList.add('active');
    tab.style.backgroundColor = 'rgba(0, 123, 255, 0.9)';
    tab.style.color = 'white';

    panel.style.display = 'block';
}

function showNotification(message, type = 'success') {
    const notification = document.createElement('div');
    const bgColor = type === 'success' ? 'rgba(40, 167, 69, 0.9)' : 'rgba(220, 53, 69, 0.9)';

    notification.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: ${bgColor};
        color: white;
        padding: 10px 15px;
        border-radius: 8px;
        box-shadow: 0 4px 10px rgba(0,0,0,0.2);
        z-index: 9999999;
        opacity: 0;
        transition: opacity 0.3s ease;
    `;

    notification.textContent = message;
    document.body.appendChild(notification);

    setTimeout(() => notification.style.opacity = '1', 10);
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => document.body.removeChild(notification), 300);
    }, 2000);
}

function filterJobsByKeywords(jobDescriptions) {
    const excludeKeywords = [];
    const includeKeywords = [];

    return jobDescriptions.filter(description => {
        for (const keyword of excludeKeywords) {
            if (description.includes(keyword)) {
                return false;
            }
        }

        if (includeKeywords.length > 0) {
            return includeKeywords.some(keyword => description.includes(keyword));
        }

        return true;
    });
}
